<script setup>
import { onBeforeMount, reactive, toRefs,ref,computed  } from 'vue';
import { deleteNamespaceHandler as deleteHandler, getNamespaceListHandler as getListHandler, createNamespaceHandler as createHandler, copyNamespacetHandler, getNamespaceDetailHandler } from '../../api/namespace.js';
import { listClusterHandler  } from '../../api/cluster.js';
import {useRoute} from 'vue-router'
import { ElMessage  } from 'element-plus'
import Edit from './Edit.vue'
import Detail from './Detail.vue'
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue';
import { listHandler } from '../../api/Generic';
const route = useRoute()
const data = reactive({
  items: [],
  clusterList: [],
  clusterId: "",
  editItem: {},
  editName: "",
  detailItem: {},
  detailName: "",
  createName: "",
  deleteName: "",
  deleteNameConfirm: "",
  sourceSourceList: {},
  namespaceDetail: [],
  copyForm: {
    clusterId: "", // 源id
    namespace: "", // 源namespace
    destClusterId: "", // 目标id
    destNamespace: "", // 目标namespace
    createNamespace: false, // 是否创建名称空间
    resources: {  // 复制的目标资源
      Deployment: [],
      StatefulSet: [],
      DaemonSet: [],
      Service: [],
      ConfigMap: [],
      Secret: [],
      CronJob: [],
      Ingress: []
    }
  }
})

const resourceList = computed(() => {
  return Object.keys(data.copyForm.resources)
})
const editDialog = ref(false)
const detailDialog = ref(false)
const createNamespaceDialog = ref(false)
const deleteNamespaceDialog = ref(false)
const showNamespaceCopy = ref(false)
const copyFormRef = ref('')
const activeName = ref('copyDest')
// 获取列表
const getList = (clusterId) => {
  console.log("查询集群:", clusterId)
  editDialog.value = false
  getListHandler(clusterId).then((response)=>{
    console.log("response:", response.data.data.items)
    data.items = response.data.data.items
    // editDialog.value = false
  })
}
// 拷贝
const copy = (row) => {
  console.log("复制Namespace:", row)
  activeName.value = 'copyDest'
  showNamespaceCopy.value = true
  data.copyForm.clusterId = data.clusterId
  data.copyForm.namespace = row.metadata.name
}
// 编辑
const edit = (row) => {
  console.log("编辑Namespace:", row)
  data.editItem = row
  data.editName = row.metadata.name
  editDialog.value = true
}
// 删除namespace
const deleteNamespace = (row) => {
  console.log("删除namespace:", row.metadata.name)
  data.deleteName = row.metadata.name
  deleteNamespaceDialog.value = true
}
const submitDeleteNamespace = () => {
  console.log("删除namespace:", data.deleteName)
  if (data.deleteName != data.deleteNameConfirm) {
    ElMessage({
        message: "删除失败: 确定删除的名称不正确",
        type: 'warning',
    })
    return
  }
  // 调用创建namespace的接口
  deleteHandler(data.clusterId, data.deleteName).then((response)=>{
    ElMessage({
        message: response.data.message,
        type: 'success',
    })

    // 查询新列表
    getList(data.clusterId)
    // 关闭弹窗
    deleteNamespaceDialog.value = false
    data.deleteNameConfirm = ""
  })
}
// 展示数据的方法
const detail = async (row) => {
  data.detailName = row.metadata.name
  await getNamespaceDetailHandler(data.clusterId, data.detailName).then((res) => {
    data.namespaceDetail = res.data.data.items
    console.log("namespaceDetail:", res.data.data.items,"namespace:",data.detailName)
  })
  detailDialog.value= true
}
const getClusterList = async () => {
  await listClusterHandler().then(
    (res) => {
      data.clusterList = res.data.data.items
    }
  )
}
const createNamespace = ()=> {
  createNamespaceDialog.value = true
}
const submitCreateNamespace = () => {
  console.log("创建namespace:", data.createName)
  // 调用创建namespace的接口
  if (data.createName == "") {
    ElMessage({
        message: "请输入名称",
        type: 'error',
    })
    return
  }
  createHandler(data.clusterId, data.createName).then((response)=>{
    ElMessage({
            message: response.data.message,
            type: 'success',
    })

    // 查询新列表
    getList(data.clusterId)
    // 关闭弹窗
    createNamespaceDialog.value = false
    data.createName = ""
  })
}

onBeforeMount(async ()=>{
  // 查询列表之前，要知道查询哪个集群的节点列表
  // 1. 查询到集群列表
  // 2. 如果没有指定集群，则给一个默认值，进行获取集群列表
  // 3. 如果指定了集群，就直接查询当前集群的节点列表
  // 4. 切换了集群之后，应该重新获取节点列表
  // 5. 集群不可用，则不可选
  // 1. 获取集群列表
  await getClusterList()
  // 2. 定义一个默认的集群
  const defaultClusterSelected = data.clusterList[0].clusterId
  console.log("默认的集群是:",defaultClusterSelected)
  // 3. 获取当前请求是否携带了集群ID的参数
  const curClusterId = route.query.clusterId // curClusterId有可能是空的
  data.clusterId = curClusterId?curClusterId:defaultClusterSelected
  getList(data.clusterId)
})
const closeDialog = () => {
  console.log("close dialog")
  getList(data.clusterId)
}
const rollback = () => {
  console.log("close dialog")
  editDialog.value = false
  getList()
}
const filterTableData = computed(() =>
  data.items.filter(
    (item) =>
      !search.value ||
      item.metadata.name.toLowerCase().includes(search.value.toLowerCase())
  )
)
const destNamespaceChanged = (destClusterId, destNamespace) => {
  data.copyForm.destClusterId = destClusterId
  data.copyForm.destNamespace = destNamespace
  console.info("目标配置:",data.copyForm)
}
const destClusterChanged = (destClusterId) => {
  data.copyForm.destClusterId = destClusterId
  console.info("目标配置:",data.copyForm)

}
const tabClick = async (pane, ev) => {
  console.log("pane", pane.props.name)
  // 获取资源列表
  if(pane.props.name != "copyDest") {
    await listHandler(data.copyForm.clusterId, data.copyForm.namespace, pane.props.name).then((res) => {
      const items = res.data.data.items
      const nameList = []
      items.forEach(item => { // 只需要name
        nameList.push({
          key: item.metadata.name,
          label: item.metadata.name
        })
      })
      data.sourceSourceList[pane.props.name] = nameList
    })
  }
  console.log("sourceSourceList",data.sourceSourceList)
  
}

const cancelNamespaceCopy = () => {
  data.copyForm.resources =JSON.parse(JSON.stringify({
    Deployment: [],
    StatefulSet: [],
    DaemonSet: [],
    Service: [],
    ConfigMap: [],
    Secret: [],
    CronJob: [],
    Ingress: []
  }))
  showNamespaceCopy.value = false
}

const submitNamespaceCopy = async () => {
  console.log("需要拷贝的数据:", data.copyForm)
  await copyNamespacetHandler(data.copyForm).then((res) => {
    ElMessage.success(res.data.message)
  })
}
const search = ref('')
const { clusterId,
        clusterList, 
        editItem, 
        editName,
        detailName,
        createName,
        deleteName,
        deleteNameConfirm,
        copyForm,
        sourceSourceList,
        namespaceDetail
        } = toRefs(data)
</script>

<template>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <div>
            <span>命名空间列表</span>
          </div>
          <div class="card-header">
            <!-- <ClusterNamespaceSelector @namespaceChangedRollback="getList"></ClusterNamespaceSelector> -->
            <el-select
            filterable
            v-model="clusterId"
            placeholder="选择集群"
            @change="getList(clusterId)"
            style="width: 180px;"
            >
              <el-option
                v-for="item in clusterList"
                :key="item.clusterId"
                :label="item.displayName"
                :value="item.clusterId"
                :disabled="item.status == 'InActive'"
              />
            </el-select>
            <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
            <el-button type="primary" style="margin-left: 10px;" @click="createNamespace">创建</el-button>
          </div>
          
        </div>
      </template>
      <!-- 放真实数据的地址，card body -->
      <el-table
      border
      height="480"
      :data="filterTableData"
      style="width: 100%"
      >
        <el-table-column fixed prop="" align="center" label="名称" width="480">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="240" sortable />
        <el-table-column prop="" align="center" label="状态" width="120" sortable>
          <template #default="scope">
            <span v-if="scope.row.status.phase == 'Active'" style="color: green;">Active</span>
            <span v-else  style="color: red;">{{ scope.row.status.phase }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" >
          <template #default="scope">
            <el-button :disabled="scope.row.metadata.deletionTimestamp" link type="primary" @click="copy(scope.row)">资源复制</el-button>
            <el-button :disabled="scope.row.metadata.deletionTimestamp" link type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button :disabled="scope.row.metadata.deletionTimestamp" link type="warning" @click="deleteNamespace(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 尾部的布局 -->
      <div class="auto-space-between" style="margin-top: 10px;">
        <!-- 总数的统计 -->
        <div></div>
        <div>总数: {{ filterTableData.length }}</div>
      </div>

    </el-card>
    <!-- 编辑namespace -->
    <el-dialog
    destroy-on-close
    @close="closeDialog"
    v-model="editDialog"
    :title="'正在编辑集群:' + clusterId + '  命名空间:' + editName"
    width="70%">
      <Edit @rollback="getList" :cluster-id="data.clusterId" :item-form="editItem"></Edit>
    </el-dialog>



    <!-- 详情 -->
    <el-dialog
    draggable
    destroy-on-close
    v-model="detailDialog"
    center
    width="70%">
      <template #header="{titleId,titleClass}">
        <div class="my-header">
          <div :id="titleId" :class="titleClass">
            <el-button type="primary" size="large" title="资源所在集群">
                <i class="iconfont icon-k8s" style="font-size: 20px"/>
                <span style="font-size: 20px;margin-left: 10px;">{{ clusterId }}</span>
            </el-button>
            <el-button type="primary" size="large" title="资源所在空间">
                <i class="iconfont icon-k8s" style="font-size: 20px"/>
                <span style="font-size: 20px;margin-left: 10px;">{{ detailName }}</span>
            </el-button>
          </div>
        </div>
      </template>
      <div class="auto-layout">
        <div v-for="item in namespaceDetail" :key="item.resourceType">
          <el-card style="width:320px;">
            <template #header>
              <span>{{ item.resourceType }}</span>
            </template>
            <div>
              <div class="auto-space-between">
                <el-icon :size="50">
                  <i :class="`iconfont icon-${item.resourceType.toLowerCase()}`" style="font-size: 40px;"/>
                </el-icon>
                <router-link :to="{
                  path: '/'+item.resourceType.toLowerCase()+'/list',
                  query: {clusterId: clusterId, namespace: detailName}
                  }">{{ item.total }}</router-link>
              </div>
            </div>
          </el-card>
        </div>
      </div>

    </el-dialog>

    <!-- 创建namespace -->
    <el-dialog
    destroy-on-close
    v-model="createNamespaceDialog"
    title="创建命名空间"
    width="30%">
      <el-input v-model.trim="createName" placeholder="请输入namespace名称"/>
      <el-button style="margin-top: 20px;" type="primary" @click="submitCreateNamespace">创建</el-button>
    </el-dialog>
    <!-- 删除namespace -->
    <el-dialog
    destroy-on-close
    v-model="deleteNamespaceDialog"
    :title="'删除命名空间:' + deleteName"
    width="30%">
      <el-input v-model.trim="deleteNameConfirm" :placeholder="'请输入要删除的名称:'+deleteName" />
      <el-button style="margin-top: 20px;" type="warning" @click="submitDeleteNamespace">删除</el-button>
    </el-dialog>

    <el-dialog
    destroy-on-close
    v-model="showNamespaceCopy"
    :title="'复制集群:' + copyForm.clusterId + ' 命名空间:' + copyForm.namespace">
      <el-form :model="copyForm" ref="copyFormRef">
        <el-tabs v-model="activeName" tab-position="left" @tab-click="tabClick">
          <el-tab-pane name="copyDest" label="复制目标">
            <el-form-item label="目标命名空间" label-width="100">
              <el-radio-group v-model="copyForm.createNamespace">
                <el-radio :value="true">新建</el-radio>
                <el-radio :value="false">选择已有</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="复制目标" label-width="100">
              <ClusterNamespaceSelector
              :show-namespace="!copyForm.createNamespace"
              @clusterChangedRollback="destClusterChanged"
              @namespaceChangedRollback="destNamespaceChanged"
              ></ClusterNamespaceSelector>
              <el-input
              v-model.trim="copyForm.destNamespace"
              v-show="copyForm.createNamespace"
              placeholder="请输入命名空间名称" style="width: 180px;margin-left: 10px;"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane :key="paneName" :name="paneName" :label="paneName" v-for="paneName in resourceList">
            <el-transfer :titles="['源','目标']" v-model="copyForm.resources[paneName]" :data="sourceSourceList[paneName]"/>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-button style="margin-top: 10px;" @click="cancelNamespaceCopy()">取消</el-button>
      <el-button style="margin-top: 10px;" type="primary" @click="submitNamespaceCopy()">复制</el-button>
    </el-dialog>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

</style>
